// pages/yourPage/yourPage.js
const { config, getApiUrl } = require('../../utils/config.js');

Page({
  data: {
    search_value: '',
    mushroomList: [],
    toxicityMap: {
      1: '无毒',
      2: '微毒',
      3: '剧毒'
    }
  },

  onLoad: function () {
    this.fetchMushrooms('');
  },

  onSearch: function (event) {
    const keyword = event.detail;
    this.fetchMushrooms(keyword);
  },

  fetchMushrooms: function (keyword) {
    wx.request({
      url: getApiUrl(config.API.SEARCH_MUSHROOM),
      method: 'GET',
      data: { keyword },
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            mushroomList: res.data.data
          });
        } else {
          wx.showToast({
            title: '未找到相关数据',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('请求失败:', error);
        wx.showToast({
          title: '请求失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  onMushroomTap(event) {
    const { index } = event.currentTarget.dataset;
    const mushroom = this.data.mushroomList[index];
    wx.navigateTo({
      url: `/pages/mushroom-detail/mushroom-detail?mushroomData=${encodeURIComponent(JSON.stringify(mushroom))}`
    });
  }
});